package com.situ.shoplook.admin.api;

import com.github.pagehelper.PageInfo;
import com.situ.shoplook.common.model.Brand;
import com.situ.shoplook.common.service.BrandService;
import com.situ.shoplook.common.service.UploadFileService;
import com.situ.shoplook.common.util.JsonResult;
import com.situ.shoplook.common.util.PaginateParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/26, last modified by 千堆雪 on 2024/8/26
 */
@RestController
@RequestMapping(value = "/api/v1/brands", produces = "application/json;charset=utf-8")
public class BrandApi {
    private BrandService brandService;
    private UploadFileService uploadFileService;

    @Autowired
    public void setBrandService(BrandService brandService) {
        this.brandService = brandService;
    }

    @Autowired
    public void setUploadFileService(UploadFileService uploadFileService) {
        this.uploadFileService = uploadFileService;
    }

    @GetMapping
    public JsonResult<Map<String, Object>> findAll(Brand search,
                                                   @RequestParam(defaultValue = "1") Integer pageNo,
                                                   @RequestParam(defaultValue = "2147383647") Integer pageSize) {
        List<Brand> list = brandService.findAll(search, PaginateParams.of(pageNo, pageSize));
        PageInfo<Brand> pageInfo = new PageInfo<>(list);
        Map<String, Object> pi = Map.of("total", pageInfo.getTotal(),
                "pages", pageInfo.getPages(),
                "pageNo", pageInfo.getPageNum(),
                "pageSize", pageInfo.getPageSize());
        return JsonResult.success(Map.of("rows", list, "pi", pi));
    }

    @PostMapping
    public JsonResult<?> save(@RequestBody Brand brand) {
        boolean success = this.brandService.save(brand);
        return JsonResult.of(success, success ? "操作成功" : "操作失败");
    }

    @PutMapping
    public JsonResult<?> update(@RequestBody Brand brand) {
        boolean success = this.brandService.update(brand);
        return JsonResult.of(success, success ? "操作成功" : "操作失败");
    }

    @DeleteMapping
    public JsonResult<?> deleteByIds(@RequestBody Integer[] ids) {
        int rows = this.brandService.deleteByIds(ids);
        return JsonResult.of(rows > 0, rows > 0 ? "操作成功，共删除" + rows + "行" : "操作失败");
    }

    /**
     * 上传品牌logo
     *
     * @return 头像
     */
    @PostMapping("/logo")
    public JsonResult<?> uploadLogo(MultipartFile file) {
        //对于分布式部署，就应该将图片上传到阿里云，或七牛云，或其它图床
        String url = this.uploadFileService.uploadImage(file, "logo");
        return JsonResult.success(url);
    }
}
